package com.qiuxi.modules.system.domain.department;

import com.qiuxi.modules.system.repository.DepartmentRepository;
import org.springframework.stereotype.Service;

import static com.cartisan.utils.AssertionUtil.requirePresent;

/**
 * @author oogundam
 * @date 2020/1/10 16:16
 **/
@Service
public class DepartmentTypeValidator {

    private final DepartmentRepository departmentRepository;

    public DepartmentTypeValidator(DepartmentRepository departmentRepository){
        this.departmentRepository = departmentRepository;
    }

    public boolean isValid(Long parentId, Integer type){
        if (parentId==0){
            return isTop(type);
        }

        return isSameLevelOrChild(parentId, type);
    }

    private boolean isTop(Integer type) {
        return type==1;
    }

    private boolean isSameLevelOrChild(Long parentId, Integer type) {
        return requirePresent(this.departmentRepository.findById(parentId)).getType().equals(type)
                || (requirePresent(this.departmentRepository.findById(parentId)).getType()+1)==type;
    }

}
